package com.jian.pipe;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;

/**
 * @author Jiange
 * @create 2021-09-13-17:20
 */
public class PipeDemo {
    public static void main(String[] args) throws IOException {
        //pipe是线程之间单向数据传输的通道 通道内又两个通道  一个是sink负责将数据写入到通道  一个是source负责读出通道
        Pipe pipe = Pipe.open();
        Pipe.SinkChannel sink = pipe.sink();
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        byteBuffer.put("李子建".getBytes());
        byteBuffer.flip();
        sink.write(byteBuffer);
        Pipe.SourceChannel source = pipe.source();
        byteBuffer.flip();
        int read = source.read(byteBuffer);
        while (read > 0){
            System.out.println(new String(byteBuffer.array(),0,read));
            byteBuffer.clear();//相当于写出   所以需要调用flip
            byteBuffer.flip();
            read = source.read(byteBuffer);
        }
        sink.close();
        source.close();
    }
}
